<template>
  <div class="callServicesList">
    <x-header class="header" :left-options="{showBack: showHeaderBack}" ref="header">呼叫服务列表</x-header>
    <div class="topHolder"></div>
    <box gap="1rem 0.8rem">
      <div class="checkerWrap" ref="checkerWrap">
        <checker v-if="loadingStatus" v-model="choosenCallType" type="radio" radio-required class="callTypeChecker" default-item-class="item" selected-item-class="selected" disabled-item-class="disabled">
          <checker-item value="-1" :disabled="loadingStatus">全部分类</checker-item>
          <checker-item value="-1" :disabled="loadingStatus">存酒</checker-item>
          <checker-item value="-1" :disabled="loadingStatus">服务</checker-item>
          <checker-item value="-1" :disabled="loadingStatus">投诉建议</checker-item>
        </checker>
        <checker v-else v-model="choosenCallType" type="radio" radio-required class="callTypeChecker" @on-change="refreshList()" default-item-class="item" selected-item-class="selected" disabled-item-class="disabled">
          <checker-item value="all">全部分类</checker-item>
          <checker-item value="1">存酒</checker-item>
          <checker-item value="2">服务</checker-item>
          <checker-item value="3">投诉建议</checker-item>
        </checker>
      </div>
      <div class="filterArea" ref="filterArea">
        <div class="filterItem">台位：<x-button @click.native="showTablesByType = true" type="default" v-html="tablesByTypeText" :show-loading="loadingStatus" :disabled="loadingStatus" class="inlineBtn popPickerBtn"></x-button></div>
        <div class="filterItem">状态：<x-button @click.native="showCallStatus = true" type="default" v-html="$refs.callStatus&&$refs.callStatus.getNameValues()+'<i class=\'iconfont icon-xiangxia2\'></i>'" :show-loading="loadingStatus" :disabled="loadingStatus" class="inlineBtn popPickerBtn"></x-button></div>
      </div>
      <popup-picker @on-change="changeTablesByTypeText();refreshList()" :show.sync="showTablesByType" :show-cell="false" :data="tablesByType" :columns="3" v-model="choosenTablesByType" ref="tablesByType" class="btn_popup-picker"></popup-picker>
      <popup-picker @on-change="refreshList()" :show.sync="showCallStatus" :show-cell="false" :data="callStatus" :columns="1" v-model="choosenCallStatus" ref="callStatus" class="btn_popup-picker"></popup-picker>
    </box>
    <scroller :height="scrollerHeight" lock-x use-pulldown use-pullup :pulldown-config="pulldownDefaultConfig" @on-pulldown-loading="refreshList()" :pullup-config="pullupDefaultConfig" @on-pullup-loading="loadMoreList" ref="loadMoreScroller" >
      <div class="callServicesList">
        <a v-for="(item,index) in callServicesList" :key="index" @click="toDetail(item.CALLSERVICE_ID)">
          <form-preview class="formPreviewList label" :class="[getStateClass(item.STATE)]" :header-label="'呼叫类型：' + getType(item.TYPE)" :header-value="getState(item.STATE)" :body-items="getBody(item)"></form-preview>
        </a>
        <div class="listNoItem" v-if="callServicesList.length <= 0">暂无呼叫服务</div>
      </div>
    </scroller>
  </div>
</template>

<script>
  import {Box, Checker, CheckerItem, XButton, PopupPicker, Scroller, FormPreview } from 'vux'
  import {getTablesByType,getCallServiceIdList,getCallServiceByIds} from "../../api";
  import {message} from "../../common/util";

  export default {
    name:'callServicesList',
    data(){
      return{
        showHeaderBack:this.GLOBAL.showHeaderBack,
        loadingStatus:false,
        choosenCallType:'all',
        showCallStatus:false,
        callStatus:[
          {name: '所有状态',value: 'all'},
          {name: '未响应',value: '0'},
          {name: '已响应',value: '1'},
          {name: '已完成',value: '2'}
        ],
        choosenCallStatus:['0'],
        tablesByTypeText:'',
        showTablesByType:false,
        choosenTablesByType:['allRegion','allRegion_of_allRoomType','allRoom_in_allRegion_of_allRoomType'],
        callServicesList:[],
        idArrayList:[],
        scrollerHeight:'',
        pulldownDefaultConfig:{
          content: '下拉刷新',
          height: 40,
          autoRefresh: false,
          downContent: '下拉刷新',
          upContent: '释放后刷新',
          loadingContent: '正在刷新...',
          clsPrefix: 'xs-plugin-pulldown-'
        },
        pullupDefaultConfig:{
          content: '上拉加载更多',
          pullUpHeight: 60,
          height: 40,
          autoRefresh: false,
          downContent: '释放后加载',
          upContent: '上拉加载更多',
          loadingContent: '加载中...',
          clsPrefix: 'xs-plugin-pullup-'
        },
        currentPage: 0,
        totalItems:0,
        pageSize:8,
        onFetching:true
      }
    },
    components:{
      Box,
      Checker,
      CheckerItem,
      XButton,
      PopupPicker,
      Scroller,
      FormPreview
    },
    computed:{
      authority(){
        return this.$store.getters.getAuthorityNotice
      },
      tablesByType:{
        get () {
          return this.$store.getters.getTablesOfAll
        },
        set (value) {
          this.$store.commit('updateTablesOfAll', value)
        }
      }
    },
    methods:{
      refreshList(params){
        this.loadingStatus = true
        this.callServicesList = []
        this.currentPage = 0
        let reqParams = {
          choosenCallType:this.choosenCallType,
          choosenCallStatus:this.choosenCallStatus,
          choosenTablesByType:this.choosenTablesByType,
          authority:'global'//this.authority.callServices//暂时所有人都能看见呼叫服务列表，不设权限
        }
        getCallServiceIdList(reqParams).then((res)=>{
          if(res.status == 'success'){
            this.$nextTick(() => {
              if(this.$refs.loadMoreScroller) {
                this.$refs.loadMoreScroller.reset({top: 0})
                this.$refs.loadMoreScroller.donePulldown()
              }
              this.idArrayList = res.data
              let unAuditCount = 0
              for(let item of this.idArrayList){
                if(item.STATE == 0) unAuditCount++
              }
              this.$store.commit('updateNotifyItem',{type:'callNotice',count:unAuditCount})
              this.totalItems = res.data.length
              this.loadMoreList({callback:(params && params.callback)?params.callback:null})
            })
          }else if(res.status == 'error') {
            message({message:res.msg,type:'error'})
            console.log('getCallServiceIdList error info:', res.msg)
          }
        }).catch((err)=>{console.log('getCallServiceIdList catch info:',err)})
      },
      loadMoreList(params){
        if (this.onFetching) {
          this.onFetching = false
          setTimeout(() => {
            let reqParams = [],start = this.currentPage*this.pageSize,end = start + this.pageSize - 1
            for(var i = start; i <= end; i++){
              if(this.idArrayList[i] != undefined)reqParams.push(this.idArrayList[i])
            }
            getCallServiceByIds(reqParams).then((res)=>{
              if(res.status == 'success'){
                if(res.data.length > 0){//后端实际用这个
                  //if (this.callServicesList.length < this.totalItems) {//前端测试用这个
                  for(var i = 0; i < res.data.length; i++){
                    this.callServicesList.push(res.data[i])
                  }
                  this.currentPage++
                }else{
                  message({message:'已经加载到底了！',type:'info'})
                }
                this.onFetching = true
                this.$nextTick(() => {
                  if(this.$refs.loadMoreScroller != undefined){
                    this.$refs.loadMoreScroller.donePullup()
                    this.$refs.loadMoreScroller.reset()
                  }
                })
              }else if(res.status == 'error') {
                message({message:res.msg,type:'error'})
                console.log('getCallServiceByIds error info:', res.msg)
              }
              this.setSize()
              this.loadingStatus = false
              if(params && params.callback && typeof params.callback == 'function')params.callback()
            }).catch((err)=>{console.log('getCallServiceByIds catch info:',err)})
          }, 500)
        }
      },
      setSize(){
        let outHeight = 0
        if(this.$refs.header)
          outHeight = this.$refs.header.$el.offsetHeight + this.$refs.checkerWrap.offsetHeight + this.$refs.filterArea.offsetHeight
        let contentHeight = window.screen.height - outHeight - 150
        this.scrollerHeight = contentHeight + 'px'
      },
      getState(state){
        switch (state) {
          case 0:return '未响应';break
          case 1:return '已响应';break
          case 2:return '已完成';break
          default:return '无状态';break
        }
      },
      getStateClass(state){
        switch (state) {
          case 0:return 'red';break
          case 1:return 'orange';break
          case 2:return 'black';break
          default:return 'gray';break
        }
      },
      getType(type){
        switch (type) {
          case 1:return '存酒';break
          case 2:return '服务';break
          case 3:return '投诉建议';break
          default:return '无类型';break
        }
      },
      getBody(item){
        let list = []
        list.push({label:'最新呼叫时间',value:item.REQUEST_DATETIME})
        list.push({label:'呼叫房台',value:item.AREA + ' - ' + item.NUMBER + '（' + item.ROOM_PLATFORM_TYPE + '）'})
        if(item.STATE == 1)list.push({label:'最新响应情况',value:'[' + item.RESPONSER + ' - ' + item.response_DEPARTMENT + ']于' + item.RESPONSE_DATETIME + '响应'})
        list.push({label:'点击查看详情>>',value:''})
        /*if(item.REMARK != '')
          list.push({label:'备注',value:item.REMARK})*/
        return list
      },
      toDetail(id){
        this.$router.push({name:'呼叫服务详情',params:{callServiceId:id}})
      },
      changeTablesByTypeText(){
        this.tablesByTypeText = this.$refs.tablesByType&&this.$refs.tablesByType.getNameValues().replace(/ /g,' - ')+'<i class=\'iconfont icon-xiangxia2\'></i>'
      }
    },
    mounted(){
      return new Promise((resolve,reject)=>{
        if(this.tablesByType.length <= 0)
          getTablesByType('global').then((res)=>{
          //getTablesByType(this.authority.callServices).then((res)=>{//暂时所有人都能看见呼叫服务列表，不设权限
            if(res.status == 'success'){
              this.tablesByType = res.data
              //this.$store.commit('updateTablesOfAll', res.data)
            }else if(res.status == 'error') {
              message({message:res.msg,type:'error'})
              console.log('getTablesByType error info:', res.msg)
            }
            resolve()
          }).catch((err)=>{console.log('getTablesByType catch info:',err)})
        else resolve()
      }).then(()=>{
        switch ('global') {
          //switch (this.authority.callServices) {//暂时所有人都能看见呼叫服务列表，不设权限
          case 'local':
            this.choosenTablesByType = [this.tablesByType[0].value,this.tablesByType[0].value + '_of_allroomType','allRoom_in_' + this.tablesByType[0].value + '_of_allroomType']
            break
          default:
            this.choosenTablesByType = ['allRegion','allRegion_of_allRoomType','allRoom_in_allRegion_of_allRoomType']
        }
        setTimeout(()=>{this.changeTablesByTypeText()},200)
        this.refreshList({callback:()=>{
            window.onresize = ()=>{
              this.setSize()
            }
          }})
        this.$store.commit('updateLoadingStatus',{isLoading:false})
      })
    },
    beforeDestroy(){
      window.onresize = ()=>{}
    }
  }
</script>

<style lang="scss" scoped>
  .callServicesList{
    .callTypeChecker{
      display: flex;justify-content:space-between;
      .item{
        width:100%;text-align: center;background: #595959;color: #fff;margin: 0 0.3rem;padding:0.3rem 0;font-size: 1rem;
        &:first-child{margin-left: 0;}
        &:last-child{margin-right: 0;}
        &.selected{
          background: #FF9800;
        }
        &.disabled{
          background: #969896;
        }
      }
    }
    .filterArea{
      .filterItem{margin-top: 1rem;}
    }
  }
</style>
